﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Utilities.Common;
using System.Collections;

namespace Utilities.UI
{
    public static class GridViewExtensions
    {
      /*  public static long GetRowId(this GridView grd, )
        {
            return long.Parse(grd.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString());
        }*/

        public static void Fill(this GridView grd, object dataSource)
        { 
            grd.DataSource = dataSource;
            if (dataSource is System.Collections.IList)
            {
                IList data = dataSource as IList;
                if (data.Count != 0)
                {
                    ClassInfo info = ClassInfoCache.GetClassInfo(data[0]);
                    grd.DataKeyNames = new string[] { info.Properties.PropId.Name };
                }
            }
            grd.DataBind();
        }

        public static object GetItem(this GridView grd, object dataSource, GridViewCommandEventArgs e)
        {
            return GetItem(grd, dataSource, int.Parse(e.CommandArgument.ToString()));
        }
        public static object GetItem(this GridView grd, object dataSource, int index)
        {
            object id = grd.DataKeys[index].Value;

            if (dataSource is System.Collections.IList)
            {
                IList data = dataSource as IList;
                if (data.Count != 0)
                {
                    ClassInfo info = ClassInfoCache.GetClassInfo(data[0]);
                    foreach (var item in data)
                    {
                        if (info.Properties.PropId.GetValue(item).ToString() == id.ToString())
                        {
                            return item;
                        }
                    }
                }
            }

            return null;
        }
        public static T GetItem<U, T>(this GridView grd, U dataSource, GridViewCommandEventArgs e) where U : List<T>
        {
            object id = grd.DataKeys[int.Parse(e.CommandArgument.ToString())].Value;

            if (dataSource.Count != 0)
            {
                ClassInfo info = ClassInfoCache.GetClassInfo(dataSource[0]);
                foreach (var item in dataSource)
                {
                    if (info.Properties.PropId.GetValue(item).ToString() == id.ToString())
                    {
                        return item;
                    }
                }
            }

            return default(T);
        }


    }
}
